// app.js
const { httpPost } = require('./pages/common/js/http')

// "customtabbar": ""
App({
  onLaunch() {
    if (wx.getUserProfile) {
      this.globalData.canIUseGetUserProfile = true
    }
    // wx.hideTabBar()
    // 展示本地存储能力
    // const logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)
    //重写分享方法
    // wx.onAppRoute(function (res) {
    //   //获取加载的页面
    //   let pages = getCurrentPages(),
    //     //获取当前页面的对象
    //     view = pages[pages.length - 1] || {};
    //   if(view.route != 'pages/evaluation/evaluationDetail/evaluationDetail' && view.route != 'pages/articleDetail/articleDetail'){
    //     //文章详情和测评详情分享调用自己的分享
    //     view.onShareAppMessage = function () {
    //       //分享配置
    //       return {
    //         title: '海星智慧生涯', // 子页面的title
    //         path: 'pages/index/index',
    //         // imageUrl: '/images/icon/logo.png'
    //         imageUrl: ''
    //       };
    //     }
    //   }
    // })

    // 登录
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //     this.globalData.code = res.code;
    //   }
    // })
    this.getOpenid()
    // 获取用户信息
    wx.getSetting({
      success: res => {
       console.log(res)
        if (res.authSetting['scope.userInfo']) {
          console.log("已经授权")
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          if(this.globalData.canIUseGetUserProfile){
            console.log("app.globalData.canIUseGetUserProfile:",this.globalData.canIUseGetUserProfile)
            wx.getUserProfile({
              desc: '用于完善会员资料',
              success: res => {
                console.log('新方法获取用户信息：',res)
                this.setData({
                  isLogin: true
                })
                //静默授权
                this.getMemberId({encryptedData:res.encryptedData,iv:res.iv})
              },
              fail:error=>{
                console.log("error:",error)
              },
              complete:res=>{
                console.log("complete:",res)
              }
            })
          }else{
            wx.getUserInfo({
              success: res => {
                // 可以将 res 发送给后台解码出 unionId
                //静默授权
                this.getMemberId({encryptedData:res.encryptedData,iv:res.iv})
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              },
            })
            if(res.userInfo.nickName&&res.userInfo.avatarUrl){
              this.setData({
                isLogin: true
              })
            }
          }
          // wx.getUserInfo({
          //   success: res => {
          //     // 可以将 res 发送给后台解码出 unionId
          //     console.log("res0:",res)
          //     this.globalData.userInfo = res.userInfo
          //     //静默授权
          //     this.getMemberId({encryptedData:res.encryptedData,iv:res.iv})

          //     // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          //     // 所以此处加入 callback 以防止这种情况
          //     if (this.userInfoReadyCallback) {
          //       this.userInfoReadyCallback(res)
          //     }
          //   },
          //   fail:(e) =>{
          //   },
          //   complete: () => {
          //   }
          // })
        }
      }
    })
  },
  globalData: {
    jsCode:"",
    userInfo: null,
    baseURL: 'https://service.haixinghr.cn',
    code: '',
    openid: '',
    canIUseGetUserProfile: false,
    tabBar: {
      "backgroundColor": "#ffffff",
      "color": "#979795",
      "selectedColor": "#1c1c1b",
      "list": [
        {
          "pagePath": "/pages/index/index",
          "iconPath": "icon/icon_home.png",
          "selectedIconPath": "icon/icon_home_HL.png",
          "text": "首页"
        },
        {
          "pagePath": "/pages/growUp/growUp",
          "iconPath": "icon/icon_release.png",
          "selectedIconPath": "icon/icon_release_HL.png",
          "text": "成长"
        },
        {
          "pagePath": "/pages/user/user",
          "iconPath": "icon/icon_mine.png",
          "selectedIconPath": "icon/icon_mine_HL.png",
          "text": "我的"
        }
      ]
    }
    
  },
  getOpenid(){
    let that = this;
    return new Promise( ( resolve , reject ) => {
      wx.login({
        success: res =>{
          console.log("userinfo:",res)
          this.globalData.code = res.code
          wx.request({
            url: that.globalData.baseURL + '/app/user/ordinary/xcxAuthLogin',
            data:{
              jsCode : res.code
            },
            header: {
              "Content-Type": "application/json"
            },
            method: "POST",
            success: openidData => {
              console.log("openidData:",openidData)
              if(openidData.data.errorCode == 0 &&  openidData.data.data){
                that.globalData.userInfo = openidData.data.data
                that.globalData.openid = openidData.data.data.openId
                wx.setStorageSync("memberInfo",openidData.data.data)
                resolve('success');
              }else {
               console.log('获取OpenId失败');
               wx.login({
                success: res =>{
                  if(res.code){
                    this.globalData.code = res.code;
                  }else{
                    reject(0)
                  }
                }
              })
              }
            }
          })
        }
      })
    })
  },
  wxLogin(){
    return new Promise ( ( resolve , reject ) => {
      wx.login({
        success: res =>{
          if(res.code){
            this.globalData.code = res.code
            resolve(res.code)
          }else{
            reject(0)
          }
        }
      })
    })
  },
  //静默授权
  getMemberId: function (data,cb) {
    console.log('getMemberIdcode:', this.globalData.code)
          let sendData = {
            jsCode:this.globalData.code,
            encryptedData: data.encryptedData,
            iv: data.iv
          }
          httpPost({
            url: "/app/user/ordinary/xcxAuthLogin",
            data: sendData,
            isLoding: false,
            lodingMsg: '正在登录...'
          }).then(res => {
            console.log("getMemberId:",res)
            if(res.errorCode == 0){
              this.globalData.userInfo = res.data
              this.globalData.openid = res.data.openId
              wx.setStorageSync("memberInfo",res.data)
              if(cb && typeof cb == 'function'){
                cb()
              }
            }
          })
   
  },
  editTabbar: function () {
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  }
})
